import React, { memo, useState, useEffect } from 'react'
import classNames from 'classnames'
import './style.less'
import { Button, Space } from 'antd'
import { HsAdminInput, HsAdminSpin, HsAdminTablePage } from '@hs-admin/base-components'
import { useSearchParams, useNavigate } from 'react-router-dom'
import { usePage } from '@hs-admin/utils'
import { handleButtonShow } from '@/utils/tools'
import { reqDataDomainList } from '@/api/assetMaintain/industry/domain'
import { reqMapList } from '@/api/assetMaintain/industry/atlas'

const ThemeDetail: React.FC = () => {
  const [searchParams]: any = useSearchParams()
  const [choseDomainId, setchoseDomainId] = useState(searchParams.get('id')) // 选择的id
  const [choseDomainName, setchoseDomainName] = useState('')
  const [choseDomainDes, setchoseDomainDes] = useState('')
  const [domainList, setdomainList] = useState<any[]>([])
  const [searchValue, setsearchValue] = useState<string>('')
  const [loading, setloading] = useState(true)

  const columns: any[] = [
    {
      title: '产业数仓名称',
      dataIndex: 'name'
    },
    {
      title: '关联图谱名称',
      dataIndex: 'map_name'
    },
    {
      title: '关联图谱ID',
      dataIndex: 'map_id'
    },
    {
      title: '产业数仓描述',
      dataIndex: 'description',
      ellipsis: true
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      type: 'datetime'
    },
    {
      title: '操作',
      dataIndex: 'action',
      render: (_: any, record: any) => (
        <>
          <Button type="link" onClick={() => handleGoDetail(record)}>
            详情
          </Button>
        </>
      )
    }
  ]
  const [data, setdata] = useState<any[]>([])
  const navigate: any = useNavigate()
  const source = searchParams.get('source')

  // 获取数据-领域列表
  const getDomainList = async () => {
    setloading(true)
    const res = await reqDataDomainList({ state: 1, page: 1, page_size: 99, status: 'published' })
    res.items.unshift({ name: '全部', id: null })
    setdomainList(res.items)
    const findItem = res.items.find((item: any) => item.id === choseDomainId)
    setchoseDomainName(findItem?.name)
    setchoseDomainDes(findItem?.description)
    setloading(false)
  }
  // 领域点击
  const handleDomainClick = (item: any) => {
    setchoseDomainId(item.id)
    setchoseDomainName(item.name)
    setchoseDomainDes(item.description)
    resetPage()
  }
  // 获取数据-数据项列表
  const getMapList = async () => {
    setdata([])
    const params = {
      page: pagination.current,
      page_size: pagination.pageSize,
      domain_id: choseDomainId,
      keywords: searchValue || undefined,
      status: 'published'
    }
    const res = await reqMapList(params)
    setdata(res.items)
    return res
  }
  const { pagination, resetPage, initPage } = usePage(getMapList)

  // 去详情
  const handleGoDetail = (record: any) => {
    navigate(`/marketIndustryData/themeDetail/dataItemDetail?id=${record.id}`)
  }
  // 搜索按钮
  const handleSearchClick = () => {
    initPage()
  }
  const openDemandOrder = () => {
    const url = `/dataService?newOrder=true&order_type=产业数仓订单`
    window.open(url, '_blank')
  }

  useEffect(() => {
    getDomainList()
  }, [])

  return (
    <div className="themeDetail">
      {loading && <HsAdminSpin />}
      {!source && (
        <div className="top">
          {domainList.map((item, index) => (
            <div className={classNames('top_item', { isActive: item.id === choseDomainId })} key={index} onClick={() => handleDomainClick(item)}>
              {item.name}
            </div>
          ))}
        </div>
      )}

      <div className="mid">
        <div className="mid_title">
          <div>{choseDomainName}</div>
          {!source && handleButtonShow('datashop.demand_order.create') && (
            <Button type="primary" onClick={openDemandOrder}>
              去下单
            </Button>
          )}
        </div>

        <div className="my-4 break-words">{choseDomainDes}</div>

        <Space align="center">
          <span>产业数仓名称：</span>
          <HsAdminInput
            defaultValue={searchValue}
            placeholder="请输入产业数仓、图谱名称、图谱ID"
            className="min-w-100"
            onChange={(e: { target: { value: React.SetStateAction<string> } }) => setsearchValue(e.target.value)}
            onPressEnter={(e: { target: { value: React.SetStateAction<string> } }) => {
              setsearchValue(e.target.value)
              handleSearchClick()
            }}
          />
          <Button type="primary" onClick={handleSearchClick}>
            搜索
          </Button>
        </Space>

        <div className="content">
          <HsAdminTablePage columns={columns} rowKey="id" dataSource={data} pagination={pagination} />
        </div>
      </div>
    </div>
  )
}

export default memo(ThemeDetail)
